import 'package:flutter/material.dart';
import 'package:flutter_1/utils/db/DatabaseHelper.dart';
import 'package:flutter_1/utils/db/InsertUser.dart';
import 'package:flutter_1/utils/image_url.dart';
import 'package:flutter_1/utils/language/message.dart';
import 'package:flutter_1/utils/language/messages_controller.dart';
import 'package:flutter_1/utils/popup_menu_button_widget.dart';
import 'package:flutter_1/utils/screen_size.dart';
import 'package:flutter_1/utils/style.dart';
import 'package:flutter_1/views/order_management_page_desktop.dart';
import 'package:get/get.dart';

/// 登陆页面
class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  MessagesController messagesController = Get.put(MessagesController());
  // 用户
  TextEditingController userController = TextEditingController();
  FocusNode userFocusNode = FocusNode();
  // 密码
  TextEditingController pswController = TextEditingController();
  FocusNode pswFocusNode = FocusNode();
  // 角色
  TextEditingController roleController = TextEditingController();
  FocusNode roleFocusNode = FocusNode();
  bool _isPasswordVisible = false; // 控制密码是否可见
  String _selectedRole = Strem.trader; // 初始化选中的角色为“贸易商”
  String _selectedLanguage = '中文'; // 初始化选中的语言为“中文”
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    insertData();
  }

  /// 插入数据
  insertData() async {
    // 贸易商插入数据

    var result = await DatabaseHelper.query('Merchant_table',
        where: 'id = ?', whereArgs: [1]);
    if (result.isEmpty) {
      // 插入数据
      await DatabaseHelper.insert("Merchant_table", {
        "id": 1,
        "merchant_name": "admin",
        "phone": "18056888000",
        "password": "admin"
      });
    } else {
      // 数据已存在
      debugPrint('ID already exists');
    }
    // 用户插入数据
    try {
      await Insertuser.insert(
          'user1', "user1", "user1", "18056888111", "1899999999@qq.com");
    } catch (e) {
      debugPrint("Error: $e");
      // 可以展示给用户相关的提示
    }
  }

  // 检查贸易商账号
  checkIsMerchant() async {
    List<Map<String, dynamic>> res = await DatabaseHelper.query(
        'Merchant_table',
        where: 'merchant_name=? AND password = ?',
        whereArgs: [userController.text, pswController.text]);
    if (res.isEmpty) {
      Get.snackbar(
        Strem.error,
        Strem.accountUnExit,
      );
    } else {
      Get.to(OrderManagementPageDesktop(
        name: userController.text,
        num: 0,
      ));
    }
  }

  // 检查客户账号
  checkIsUser() async {
    List<Map<String, dynamic>> res = await DatabaseHelper.query('User_table',
        where: 'name=? AND password = ?',
        whereArgs: [userController.text, pswController.text]);
    if (res.isEmpty) {
      Get.snackbar(
        Strem.error,
        Strem.accountUnExit,
      );
    } else {
      Get.to(OrderManagementPageDesktop(
        name: userController.text,
        num: 1,
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 失去焦点
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Center(
              child: Stack(
            children: [
              Container(
                alignment: Alignment.center,
                width: ScreenSize.screenWidth(context) * 0.8,
                margin: EdgeInsets.only(top: 50),
                padding:
                    const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                decoration: BoxDecoration(
                    color: Style.c_white,
                    borderRadius: BorderRadius.circular(10)),
                child: Column(
                  children: [
                    Image.asset(
                      ImageUrl.logo,
                      width: 60,
                    ),
                    Text(
                      Strem.title,
                      style: Style.loginTitle,
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    _inputView(userController, userFocusNode),
                    _inputView(pswController, pswFocusNode),
                    _inputView(roleController, roleFocusNode),
                    ScreenSize.height(15),
                    GestureDetector(
                      onTap: () {
                        if (userController.text == "") {
                          Get.snackbar(
                            Strem.error,
                            '${Strem.username}${Strem.unempty}',
                          );
                          return;
                        }
                        if (pswController.text == "") {
                          Get.snackbar(
                              Strem.error, '${Strem.psd}${Strem.unempty}');
                          return;
                        }
                        if (_selectedRole == Strem.trader) {
                          checkIsMerchant();
                        } else {
                          checkIsUser();
                        }
                      },
                      child: Container(
                        width: ScreenSize.screenWidth(context) * 0.8 - 40,
                        padding: EdgeInsets.symmetric(vertical: 10),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Style.c_8cd5ff,
                            borderRadius: BorderRadius.circular(5)),
                        child: Text(
                          Strem.login,
                          style: Style.c_white_size18,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Positioned(
                  top: 20,
                  right: 0,
                  child: Container(
                    decoration: BoxDecoration(
                        color: Style.c_back12,
                        borderRadius: BorderRadius.circular(5)),
                    child: PopupMenuButtonWidget.popupMenu(
                        _selectedLanguage, languageList(), (String newValue) {
                      setState(() {
                        _selectedLanguage = newValue; // 更新选中的角色
                        if (_selectedLanguage == '中文') {
                          messagesController.changeLanguage('zh', "CN");
                        } else if (_selectedLanguage == 'English') {
                          messagesController.changeLanguage('en', "US");
                        } else if (_selectedLanguage == 'ไทย') {
                          messagesController.changeLanguage('th', "TH");
                        } else if (_selectedLanguage == 'Français') {
                          messagesController.changeLanguage('fr', "FR");
                        } else if (_selectedLanguage == 'Deutsch') {
                          messagesController.changeLanguage('de', "DE");
                        } else if (_selectedLanguage == '日本語') {
                          messagesController.changeLanguage('ja', "JP");
                        }
                      });
                    }),
                  ))
            ],
          )),
        ),
      ),
    );
  }

  /// 语言列表
  List<PopupMenuEntry<String>> languageList() {
    List<PopupMenuEntry<String>> list = [];
    List language = ["中文", "English", "ไทย", "Français", "Deutsch", "日本語"];
    for (var data in language) {
      list.add(
        PopupMenuItem(
          value: data,
          child: Text(data, style: const TextStyle(color: Colors.white)),
        ),
      );
    }
    return list;
  }

  /// 输入框、选择框
  Widget _inputView(TextEditingController controller, FocusNode foc) {
    String img = '';
    String name = '';
    Widget widget = Container();
    if (controller == userController) {
      img = ImageUrl.user;
      name = Strem.username;
      widget = TextField(
        controller: controller,
        focusNode: foc,
        decoration: const InputDecoration(
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(horizontal: 10),
        ),
      );
    } else if (controller == pswController) {
      img = ImageUrl.psw;
      name = Strem.psd;
      widget = TextField(
        controller: controller,
        focusNode: foc,
        obscureText: !_isPasswordVisible, // 根据状态决定是否隐藏密码
        textAlignVertical: TextAlignVertical.center, // 文字垂直居中
        decoration: InputDecoration(
          border: InputBorder.none,
          contentPadding: const EdgeInsets.symmetric(horizontal: 10),
          suffixIcon: IconButton(
            icon: Icon(
              _isPasswordVisible ? Icons.visibility : Icons.visibility_off,
              color: Colors.grey, // 图标颜色
            ),
            onPressed: () {
              setState(() {
                _isPasswordVisible = !_isPasswordVisible; // 切换密码可见状态
              });
            },
          ),
        ),
      );
    } else if (controller == roleController) {
      img = ImageUrl.roleManagement;
      name = Strem.role;
      widget = PopupMenuButtonWidget.popupMenu(_selectedRole, [
        PopupMenuItem(
          value: Strem.trader,
          child: Text(Strem.trader, style: TextStyle(color: Colors.white)),
        ),
        PopupMenuItem(
          value: Strem.client,
          child: Text(Strem.client, style: TextStyle(color: Colors.white)),
        ),
      ], (String newValue) {
        setState(() {
          _selectedRole = newValue; // 更新选中的角色
        });
      });
    }
    return Column(
      children: [
        Row(
          children: [
            Image.asset(
              img,
              width: 30,
            ),
            ScreenSize.width(10),
            Text(
              name,
              style: Style.c_back54_size18,
            )
          ],
        ),
        ScreenSize.height(15),
        Container(
          decoration: BoxDecoration(
              color: Style.c_back12, borderRadius: BorderRadius.circular(5)),
          width: ScreenSize.screenWidth(context) * 0.8 - 40,
          child: widget,
        ),
        ScreenSize.height(15),
      ],
    );
  }
}
